﻿using Furion;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using BaseNet.Application;
using SqlSugar;
using System.IO;
using System.Text.Json;
using CSRedis;
using Hangfire;
using BaseNet.Web.Core.Filter;

namespace BaseNet.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);//开启全局接口授权

            services.AddCorsAccessor();

            services.AddControllers()
                    .AddInjectWithUnifyResult<RESTfulResultProvider>();

            services.AddControllersWithViews()
                    //.AddMvcFilter<RequestAuditFilter>()//添加审计日志
                    .AddNewtonsoftJson(options =>
                    {
                        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    });


            //配置sqlsugar数据库
            services.AddSqlSugar(new ConnectionConfig
            {
                ConnectionString = App.Configuration["ConnectionStrings:BaseNetDB"],//连接BaseNetDB符字串
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
            }, o => o.QueryFilter.Add(new SqlFilterItem
            {
                FilterValue = filterDb =>
                {
                    return new SqlFilterResult()
                    {
                        Sql = "IsDeleted!=1"
                    };
                },
                IsJoinQuery = false
            }));

            //配置redis缓存
            RedisHelper.Initialization(new CSRedisClient("127.0.0.1:6379,defaultDatabase=0"));

            //配置hangfire
            services.AddHangfire(configuration => configuration.UseSqlServerStorage(App.Configuration["ConnectionStrings:BaseNetDB"]));
            services.AddHangfireServer();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            #region 配置上传文件访问路径
            string savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
            //判断是否存在文件上传目录，若不存在，则创建
            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);//存在？不存在就创建
            //通过url访问文件
            app.UseStaticFiles(new StaticFileOptions()//自定义自己的文件路径
            {
                RequestPath = new PathString("/uploads"),//对外的访问路径
                FileProvider = new PhysicalFileProvider(savePath)//指定实际物理路径
            });
            #endregion

            #region 配置hangfire任务
            app.UseHangfireDashboard("/hangfire", new DashboardOptions()
            {
                Authorization = new[] { new CustomAuthorizeFilter() }
            });
            #endregion
        }
    }
}